import axios from "axios";
import qs from "qs";
const pending = new Map();
// 添加请求
const addPending = (config) => {
  const url = [
    config.method,
    config.url,
    qs.stringify(config.data ? config.data : config.params),
  ].join("&");
  if (pending.has(url)) {
    config.cancelToken = new axios.CancelToken((cancel) =>
      cancel(`重复请求被主动拦截:${url}`)
    );
  } else {
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        pending.set(url, cancel);
      });
  }
};

// 移除请求
const remvoePending = (config) => {
  const url = [
    config.method,
    config.url.replace(config.baseURL, ""), // 响应url会添加域名，需要去掉与请求url保持一致
    qs.stringify(config.data ? config.data : config.params), // 需要与request的参数结构保持一致，request中是对象,response中是字条串
  ].join("&");
  if (pending.has(url)) {
    pending.delete(url);
  }
};

const clearPending = () => {
  for (const [url, cancel] of pending) {
    cancel(url);
  }
  pending.clear();
};

export default {
  addPending,
  remvoePending,
  clearPending,
};
